package com.wskj.common.utils.ali;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.wskj.common.utils.common.AssertUtils;

public class AliLoginUtils {

    /**
     * 换取授权访问令牌通过用户Code
     * @param appId
     * @param privateKey
     * @param code
     * @return
     * @throws AlipayApiException
     */
    public static AlipaySystemOauthTokenResponse getValidAuth(String appId,String privateKey,String code){
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",appId,privateKey);
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(code);
        request.setGrantType("authorization_code");
        request.setRefreshToken("201208134b203fe6c11548bcabd8da5bb087a83b");
        AlipaySystemOauthTokenResponse response = null;
        try{
            response = alipayClient.execute(request);
            System.out.println(response.getBody());
            if (response.isSuccess()) {
                System.out.println("调用成功");
            } else {
                AssertUtils.isTrue(Boolean.FALSE,response.getMsg());
            }
        }catch (AlipayApiException e){
            AssertUtils.isTrue(Boolean.FALSE,e.getErrMsg());
        }
        return response;
    }

    public static AlipayUserInfoShareResponse userInfo(String appId,String privateKey,String publicKey,String accessToken){
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",appId,privateKey,"json","GBK",publicKey,"RSA2");
        AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
        AlipayUserInfoShareResponse response = null;
        try {
            response = alipayClient.execute(request,accessToken);
        } catch (AlipayApiException e) {
            throw new RuntimeException("调用支付宝第三方失败");
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            return response;
        } else {
            System.out.println("调用失败");
            return null;
        }
    }
}
